<?php
/**
 * Created by PhpStorm.
 * User: locove
 * Date: 15-3-24
 * Time: 上午11:48
 */
class Controller_Wishsales extends Controller
{
    public function action_wishcron()
    {
        $page = 1;
        $start = date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']);
        $from = DB::select(DB::expr('DATE_FORMAT(add_time,"%Y-%m-%d") date'))
            ->from('wish_sales')->order_by('id','DESC')
            ->limit(1)->execute('newerp')->get('date',0);

        $end  = date('Y-m-d',$_SERVER['REQUEST_TIME']);

        $tbls = self::getTbls($_SERVER['REQUEST_TIME'],$from?1:30);
        $from = $from?$from:date('Y-m-d',strtotime('-30 days',$_SERVER['REQUEST_TIME']));

        $l = count($tbls)-1;
        $sqls = array();
        foreach($tbls as $m=>$tbl)
        {
            $sql = "(SELECT
                            `{$tbl}`.`sku` sku,
                             SUM(`{$tbl}`.`sku_quantity`) num,
                             DATE_FORMAT(`{$tbl}`.`add_time`,'%Y-%m-%d') date,
                             '{$start}' addTime
                       FROM
                            `{$tbl}`
                      ";
            if($l==0)
            {
                $sql .= " WHERE `{$tbl}`.add_time>='{$from}'
                        AND `{$tbl}`.add_time<'{$end}' ";
            }else{
                if($m == $l)
                    $sql .= " WHERE `{$tbl}`.add_time<'{$end}' ";
                else
                    $sql .= " WHERE `{$tbl}`.add_time>='{$from}' ";
            }

            $sql .= "GROUP BY `{$tbl}`.`SKU`,DATE_FORMAT(`{$tbl}`.`add_time`,'%Y-%m-%d'))";

            $sqls[] = $sql;
        }
        $sqls = join(" UNION ALL ",$sqls);

        $sql = "SELECT
                    a.sku,a.num,a.date,'{$start}'
                FROM
                    ({$sqls}) a";

        $count = 0;
        while(stagerpc::getWishSkuSales($sql." LIMIT ".($page++ -1)*500 . ',500',$data))
        {
            foreach($data as &$v)
            {
                $v = '("'.join('","',tool::slashesDeep($v)).'")';
                $count ++;
            }

            $data = "INSERT INTO `wish_sales` (`sku`,`sale`,`count_date`,`add_time`)
                    VALUES ".join(",",$data);

            DB::query(Database::INSERT,$data)->execute('newerp');
        }

        checkstock::bomb('wish',$from);
        checkstock::badBegin('wish');
        checkstock::activeOut(4, $from);
        $mid = time() - $_SERVER['REQUEST_TIME'];
        echo '开始时间'.$start.',导入'.$count.'条数据,耗时'.$mid."秒\n";
    }

    //获取某个时间段的所有表后缀
    public function getTbls($t,$f)
    {
        $tbls = array();

        $now    = str_replace('20','',str_replace('-','',date("Y-m",$t)));
        $back   = str_replace('20','',str_replace('-','',date("Y-m",strtotime("- {$f}days",$t))));

        $c = $now-$back;

        if($c>3)//如果跨年
        {
            $tbls[] = 'wish_products'.($back);
            $tbls[] = 'wish_products'.($now);
        }else{//如果包含2月份
            for($i=0;$i<=$c;$i++)
            {
                $tbls[] = 'wish_products'.($back+$i);
            }
        }

        return $tbls;
    }
}